<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    // 函数柯里化 //
    函数柯里化是指将一个多参数的函数转化为多个单参数的函数，并且返回一个新的函数，
    // 新的函数可以接收剩余的参数，并且返回最终的结果。 1、简单实列
    <script>
      // sum(1,2) 变成sum(1)(2)
      // function sum(a,b){
      //   return a + b
      // }
      function sum(a) {
        return function (b) {
          return a + b
        }
      }
      console.log('sum(1)(2)', sum(1)(2))
    </script>
    <!-- 2、复杂实例sum(1)(2)(3)(4)(5)或者sum(1,2)(3,4)(5)或者sum(1,2,3)(4,5)等
  分析：2.1当传入的的个数为5个的时候累加,使用数组存参数
        2.2每次传入的参数的个数是不定的，使用arguments
  注意：每次累加完数组清空      
  <script>
    let arg = []
    function sumFn(){
      arg.push(...arguments)
      if(arg.length === 5) {
        const sum = arg.slice(0,5).reduce((pre,cur)=>pre+cur,0);
        arg = []
        return sum
      }else{
        return sumFn
      }
    }
    console.log('sum(1)(2)(3)(4)(5)',sumFn(1)(2)(3)(4)(5))
    console.log('sum(1)(2)(3)(4)(5)',sumFn(1,2)(3,4)(5))
    console.log('sum(1)(2)(3)(4)(5)',sumFn(1,2,3)(9,5))
  </script> -->
    3、复杂实例改造成不定参数个数传入，最后通过()进行调用
    分析：当传入的参数个数为空的时候需要累加前面，如果不是空继续
    <script>
      let arg = []
      function sumFn() {
        // 处理这种情况 console.log('sumFn()', sumFn())
        if(arg.length === 0 && arguments.length===0) {
          return;
        }
        if (arguments.length === 0) {
          const sum = arg.reduce((pre, cur) => pre + cur, 0)
          arg = []
          return sum
        } else {
          arg.push(...arguments)
          return sumFn
        }
      }
      console.log('sumFn(1)(3)(4)(5)()', sumFn(1)(3)(4)(5)())
      console.log('sumFn(1, 2)(3, 4)(5)()', sumFn(1, 2)(3, 4)(5)())
      console.log('sumFn(1, 2)(9, 5)()', sumFn(1, 2)(9, 5)())
       console.log('sumFn()', sumFn())
    </script>
    <script>
      // 1、需要一个函数进行参数的求和，定义一个sumFN对所有参数进行求和，curring函数接收参数为fn
      function sumFn() {
        let arr = [...arguments]
        return arr.reduce((pre, cur) => {
          return pre + cur
        })
      }

      function curring(fn) {
        let args = []
        return function result(...arguments) {
          if (arguments.length == 0) {
            return fn(...args)
          } else {
            args.push(...arguments)
            return result
          }
        }
      }

      // console.log(sumFn(1,2,3,4,5))
      // console.log(curring(sumFn)(1,2)())
      console.log(curring(sumFn)(1)(2)(3)()) // 6
      console.log(curring(sumFn)(1, 2)(3, 4)(5)()) // 15
      console.log(curring(sumFn)(1)(2, 2, 3, 4, 5)(6)()) // 23
    </script>
  </body>
</html>
